import GoogleMobileAds
import SwiftUI

class InterstitialAdManager: NSObject, GADFullScreenContentDelegate, ObservableObject {
    private var interstitial: GADInterstitialAd?
    var advalue  = "-1"
    var myAdSourceId = "-1"
    var myadID = ""
    var mycu = "-1"
    var myci = "-1"
    override init() {
        super.init()
        loadInterstitial()
    }
    
    private func loadInterstitial() {
        Task {
            do {
                interstitial = try await GADInterstitialAd.load(
                    withAdUnitID: interstitiaId, request: GADRequest())
                interstitial?.fullScreenContentDelegate = self
                adLog("插页广告加载成功")
            } catch {
                
              //logData(position: "interstitial error", status: "插页广告", uid: self.myadID, info: "插页广告加载失败", currency: "", cicros: "",errorInfo :" \(error.localizedDescription)")

                
                adLog("加载插页广告失败: \(error.localizedDescription)")
            }
        }
    }
    
    func showInterstitial() {
        guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else {
            adLog("无法获取根视图控制器")
            return
        }
        if let ad = interstitial {
            
            self.interstitial = ad
               self.interstitial?.paidEventHandler = { adValue in
                   // 提取展示级广告收入数据
                   let value = adValue.value
                   let precision = adValue.precision
                   let currencyCode = adValue.currencyCode
                   
                   // 获取广告单元 ID
                   let adUnitId = ad.adUnitID
                   
                   let responseInfo = ad.responseInfo
                   let loadedAdNetworkResponseInfo = responseInfo.loadedAdNetworkResponseInfo
                   let adSourceId = loadedAdNetworkResponseInfo?.adSourceID
                   let adSourceInstanceId = loadedAdNetworkResponseInfo?.adSourceInstanceID
                   let adSourceInstanceName = loadedAdNetworkResponseInfo?.adSourceInstanceName
                   let adSourceName = loadedAdNetworkResponseInfo?.adSourceName
                   let mediationGroupName = responseInfo.extrasDictionary["mediation_group_name"]
                   let mediationABTestName = responseInfo.extrasDictionary["mediation_ab_test_name"]
                   let mediationABTestVariant = responseInfo.extrasDictionary["mediation_ab_test_variant"]
                   
                   
                   
                   self.advalue  = "\(value)"
                   self.myAdSourceId = "\(adSourceId ?? "null")"
                   if let adSourceId = adSourceId {
                      
                       self.myadID = adSourceId

                   }
                   self.mycu = currencyCode
                   self.myci = "\(value)"
                   
                 
                // logAd(type: "插页", adId:  "and i got close", value: advalue, precision: precision, currencyCode: currencyCode, adUnitId: adUnitId)
                   if let adSourceId = adSourceId {
                      // adLog("xianban: 广告来源 ID: \(adSourceId)") // 输出广告来源 ID
                   }
                   if let adSourceInstanceId = adSourceInstanceId {
                      // adLog("xianban: 广告来源实例 ID: \(adSourceInstanceId)") // 输出广告来源实例 ID
                   }
                   if let adSourceInstanceName = adSourceInstanceName {
                     //  adLog("xianban: 广告来源实例名称: \(adSourceInstanceName)") // 输出广告来源实例名称
                   }
                   if let adSourceName = adSourceName {
                      // adLog("xianban: 广告来源名称: \(adSourceName)") // 输出广告来源名称
                   }
                   if let mediationGroupName = mediationGroupName {
                     //  adLog("xianban: 中介组名称: \(mediationGroupName)") // 输出中介组名称
                   }
                   if let mediationABTestName = mediationABTestName {
                     //  adLog("xianban: 中介 AB 测试名称: \(mediationABTestName)") // 输出中介 AB 测试名称
                   }
                   if let mediationABTestVariant = mediationABTestVariant {
                      // adLog("xianban: 中介 AB 测试变体: \(mediationABTestVariant)") // 输出中介 AB 测试变体
                   }
               }
            
            
            ad.present(fromRootViewController: rootViewController)
        } else {
            loadInterstitial()
        
        }
    }
    
    // MARK: - GADFullScreenContentDelegate
    
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    }
    
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
    }
    
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      
        loadInterstitial()
        /**
         记录当日广告展示次数
         广告展示总数
         */
      
        
      //logData(position: " increase", status: "插页广告", uid: myadID, info: "插页广告价值", currency: mycu, cicros: myci)
    }
}
